import { Alert, message as Message, Modal, Spin } from 'antd'
import { dynamic, router, routerRedux } from 'dva'

import App from '@/pages/components/App'
import { loginNoMenuRoutes, loginRoutes, noLoginRoutes } from '@/router/index'
import { componentMap, modelsMap } from '@/router/modelsAndComponent'
import { setMessage, setModal } from '@/utils/antdHelper'

const { ConnectedRouter } = routerRedux
const { Route, Switch } = router

const PageDev = () => import('@/components/PageDev')

dynamic.setDefaultLoadingComponent(() => (
  <Spin wrapperClassName='w100% h100% bg-#fff ' spinning tip='页面加载中'>
    <div style={{ height: 800 }}></div>
  </Spin>
))

const returnRoute = ({ app, path, pageKey }) => (
  <Route
    exact
    key={path}
    path={path}
    render={props => {
      const ViewComponent = dynamic({
        app,
        models: modelsMap[pageKey],
        component: componentMap[pageKey] || PageDev, // 系统里定义了路由，但是未开发，显示PageDev
      })
      return (
        <Alert.ErrorBoundary>
          <ViewComponent pageKey={pageKey} {...props} />
        </Alert.ErrorBoundary>
      )
    }}
  />
)

function Routers({ history, app }) {
  const [modal, modalContextHolder] = Modal.useModal()
  const [message, messageContextHolder] = Message.useMessage()

  setModal(modal)
  setMessage(message)

  return (
    <ConnectedRouter history={history}>
      <Switch>
        {noLoginRoutes.map(({ path, pageKey }) => returnRoute({ app, path, pageKey }))}
        {loginNoMenuRoutes.map(({ path, pageKey }) => returnRoute({ app, path, pageKey }))}
        <App>{loginRoutes.map(({ path, pageKey }) => returnRoute({ app, path, pageKey }))}</App>
      </Switch>
      {modalContextHolder}
      {messageContextHolder}
    </ConnectedRouter>
  )
}

export default Routers
